package cpe.hapa.authentication;

import java.text.ParseException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery.TooManyResultsException;

import cpe.hapa.dao.UserDAO;
import cpe.hapa.model.User;

public class Authenticate {
	public static String AuthenticationKey = "userKeyString";
	
	public static Boolean authenticate(HttpServletRequest request, String login, String password) throws NumberFormatException, TooManyResultsException, ParseException, EntityNotFoundException {
		User user = UserDAO.getByLoginOrEmail(login);
		if (user==null) {
			return false;
		}
		
		if(user.getPassword().equals(password)) {
			HttpSession session = request.getSession(true);
			session.setAttribute(AuthenticationKey, KeyFactory.keyToString(user.getKey()));
			SessionHandler.addSession(user.getKey());
			return true;
		}
		
		return false;
	}
	
	public static User getConnectedUser(HttpServletRequest request) throws NumberFormatException, ParseException {
		HttpSession session = request.getSession(true);
		
		String userKeyString = (String) session.getAttribute(AuthenticationKey);
		if(userKeyString == null) {
			return null;
		}
		
		Key userKey = KeyFactory.stringToKey(userKeyString);
		if(!SessionHandler.Contains(userKey)) {
			return null;
		}
		
		return UserDAO.getByKey(userKey);
	}
	
	public static void disconnect(HttpServletRequest request) throws NumberFormatException, ParseException, EntityNotFoundException {
		HttpSession session = request.getSession(true);
		
		String userKeyString = (String) session.getAttribute(AuthenticationKey);
		if(userKeyString == null) {
			return;
		}
		
		Key userKey = KeyFactory.stringToKey(userKeyString);
		SessionHandler.deleteSession(userKey);
		session.invalidate();
	}
}
